package com.livegoods.rabbitmq.dao.impl;


import com.livegoods.pojo.House;
import com.livegoods.rabbitmq.dao.HouseDao4Redis;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class HouseDao4RedisImpl implements HouseDao4Redis {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public House get(String key) {
        ValueOperations valueOperations = redisTemplate.opsForValue();

        House house = (House) valueOperations.get(key);
        return house;
    }

    @Override
    public boolean set(String key,final House value) {

        //设置redis支持事务
        redisTemplate.setEnableTransactionSupport(true);
        Object execute = redisTemplate.execute(new SessionCallback() {

            /*执行具体修改redis操作*/
            @Override
            public Object execute(RedisOperations redisOperations) throws DataAccessException {

                //判断房屋是否已经出租
                House house = get(key);
                //如果已经出租直接返回null
                if(house.isRented()){
                    return null;
                }

                //通知redis接下来的操作原子操作（防止多个用户同时进来进行修改抢购）
                //开启事务， 通知redis后续的多条命令，是一个原子操作。
                redisOperations.multi();

                //修改内容
                redisOperations.opsForValue().set(key,value);

                //执行操作，相当于提交事务
                List exec = redisOperations.exec();

                return exec;
            }
        });
        redisTemplate.setEnableTransactionSupport(false);
        System.out.println("execute = " + execute);

        if(execute==null){
            return false;
        }
        return true;
    }
}
